package phaseListener;

import javax.faces.application.NavigationHandler;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.http.HttpSession;
import backingBean.BeanUser;

@SuppressWarnings("serial")
public class UserPhaseListenerFilter implements PhaseListener{

	@Override
	public void afterPhase(PhaseEvent event) {
	}

	@Override
	public void beforePhase(PhaseEvent event) {
		FacesContext fc = FacesContext.getCurrentInstance();
		HttpSession session = (HttpSession) fc.getExternalContext().getSession(true);
		BeanUser bbUser = (BeanUser) session.getAttribute("bbUser");
		boolean loginPage = fc.getViewRoot().getViewId().lastIndexOf("admin/index.xhtml") > -1 ? true : false;
		if(bbUser == null){
			bbUser = new BeanUser();
			if(!(loginPage) && !bbUser.getLogged()){
				NavigationHandler nh = fc.getApplication().getNavigationHandler();
				nh.handleNavigation(fc, null, "logout");
			}
		}
		else{
			if(!(loginPage) && !bbUser.getLogged()){
				NavigationHandler nh = fc.getApplication().getNavigationHandler();
				nh.handleNavigation(fc, null, "logout");
			}
		}
	}

	@Override
	public PhaseId getPhaseId() {
		return PhaseId.RENDER_RESPONSE;
	}
}
